How to use an EventEmitter with Angular?

您所在的位置:网站首页 angular 12 event emitter How to use an EventEmitter with Angular?

How to use an EventEmitter with Angular?

2023-08-09 07:04| 来源: 网络整理| 查看: 265

Sometimes, we want to use an EventEmitter with Angular.

In this article, we’ll look at how to use an EventEmitter with Angular.

How to use an EventEmitter with Angular?

To use an EventEmitter with Angular, we can use it to emit an event from the child component to the parent.

For instance, we write

@Component({ selector: "child", template: ` Notify my parent! `, }) class Child { @Output() notifyParent: EventEmitter = new EventEmitter(); sendNotification() { this.notifyParent.emit("hello parent"); } }

to create the notifyParent EventEmitter object.

Then we call notifyParent.emit in the sendNotification method that’s called when we click the button.

Then in the parent component, we write

@Component({ selector: "parent", template: ` `, }) class Parent { getNotification(evt) { // Do something with the notification (evt) sent by the child! } }

to listen for the notifyParent event emitted by the child component.

And we get the argument we call emit with in getNotification.

Conclusion

To use an EventEmitter with Angular, we can use it to emit an event from the child component to the parent.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3